﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Games.Data
{
    public static class DataBaseExtentions
    {
        public static async Task SaveRecordByLevel<T>(this IDataBase database, T newRecord, Expression<Func<T, bool>> gettor, Func<T, bool> updater) where T : GameRecords, new()
        {
            var record = await database.GetFirstOrDefaultAsync<T>(gettor);
            if(record == null)
            {
                await database.SaveAsync(newRecord);
            }
            else
            {
                if(updater(record))
                {
                    newRecord.ID = record.ID;
                    await database.SaveAsync(newRecord);
                }
            }
        }

        public static async Task SaveRecordByDiff<T>(this IDataBase database, T newRecord, int maxCount, Expression<Func<T, bool>> gettor, Func<IEnumerable<T>, IEnumerable<T>> sorter, Func<T, bool> updater) where T : GameRecords, new()
        {
            var records = await database.GetAllAsync<T>(gettor);
            records = sorter(records).ToList();
            maxCount = Math.Min(Math.Max(1, maxCount), 100);
            var record = records.Skip(maxCount - 1).FirstOrDefault();
            if(record == null)
            {
                await database.SaveAsync(newRecord);
            }
            else
            {
                if(updater(record))
                {
                    newRecord.ID = record.ID;
                    await database.SaveAsync(newRecord);
                }
            }
        }
    }
}